package com.gr.labbackend.service.Impl.manage.material;

import com.alibaba.fastjson.JSONObject;
import com.gr.labbackend.mapper.MaterialMapper;
import com.gr.labbackend.model.dto.Material;
import com.gr.labbackend.service.manage.material.UpdateMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

@Service
public class UpdateMaterialServiceImpl implements UpdateMaterialService {

    @Autowired
    private MaterialMapper materialMapper;

    // 从配置文件中读取上传目录路径
    @Value("${file.upload-dir}")
    private String uploadDir;

    @Override
    public JSONObject updateMaterial(int id, String title, MultipartFile file) {

        JSONObject resp = new JSONObject();

        if ("null".equals(title)) {
            resp.put("error_message", "标题不能为空");
            return resp;
        }

        if (title.length() > 100) {
            resp.put("error_message", "标题长度超出限制");
            return resp;
        }

        if (file == null) {
            Material material = materialMapper.selectById(id);
            material.setTitle(title);
            materialMapper.updateById(material);
            resp.put("error_message", "success");
            resp.put("fileName", material.getFileName());
            return resp;
        }

        // 生成文件名
        String newFileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
        String filePath = uploadDir + File.separator + newFileName;  // 使用 uploadDir 配置的路径

        if (file.getOriginalFilename().length() > 255) {
            resp.put("error_message", "文件名长度超出限制");
            return resp;
        }

        // 将图片保存到指定的本地目录
        try {
            Files.copy(file.getInputStream(), Paths.get(filePath));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // ServletUriComponentsBuilder 对象可以帮助构建一个相对当前服务器的 URI
        String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
                .path("/uploads/")
                .path(newFileName)
                .toUriString();

        Material material = materialMapper.selectById(id);
        material.setTitle(title);
        material.setFileName(file.getOriginalFilename());
        material.setFileUrl(fileDownloadUri);
        materialMapper.updateById(material);
        resp.put("error_message", "success");
        resp.put("fileName", file.getOriginalFilename());

        return resp;
    }
}
